<?php

namespace App\Admin\Forms;

use App\Models\WorkUser;
use App\Models\WorkTicket;
use Dcat\Admin\Widgets\Form;
use Dcat\Admin\Traits\LazyWidget;
use App\Admin\Renderable\WorkUserTable;
use Dcat\Admin\Contracts\LazyRenderable;

class SelectWorkerForm extends Form  implements LazyRenderable
{
    use LazyWidget; // 使用异步加载功能
    /**
     * Handle the form request.
     *
     * @param array $input
     *
     * @return mixed
     */
    public function handle(array $input)
    {
        // dump($input);
        $ids = explode(',', $input['id'] ?? null);  
        $workUserId = $input['work_user_id'] ?? null;

        if (is_null($ids)) {
            return $this->response()->error('请选择工单');
        }
        if (is_null($workUserId)) {
            return $this->response()->error('请选择维修人员');
        }

        WorkTicket::whereIn('id', $ids)->update(['work_user_id' => $workUserId]);
        return $this->response()->success('分配成功')->refresh();
    }

    /**
     * Build a form here.
     */
    public function form()
    {
        $this->selectTable('work_user_id', '选择维修人员')->title('选择维修人员')
            ->from(WorkUserTable::make())
            ->options(function ($v) {
                if (!$v) {
                    return [];
                }

                $arr = WorkUser::find($v)->pluck('real_name', 'id');
                return $arr;
            })->required();

        // 设置隐藏表单，传递用户id
        $this->hidden('id')->attribute('id', 'work-ticket-ids')
            ->default($this->payload['id'] ?? null);
    }

    /**
     * The data of the form.
     *
     * @return array
     */
    public function default()
    {
        return [
            'name'  => 'John Doe',
            'email' => 'John.Doe@gmail.com',
        ];
    }
}
